package org.example.yuaiagent.intercepter;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.yuaiagent.constant.SysConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.Duration;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 输出请求url和方法
        System.out.println("请求url：" + request.getRequestURI());
        System.out.println("请求方法：" + request.getMethod());

        // 如果是OPTIONS预检请求，直接放行
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            System.out.println("OPTIONS预检请求，直接放行");
            return true;
        }
        if (request.getRequestURI().startsWith("/api/v3/api-docs")) {
            System.out.println("登录请求，放行");
            return true;
        }

        String token = request.getHeader("authorization");

        if (token == null || token.isEmpty()) {
            response.setStatus(401);
            System.out.println("token为空，拦截");
            return false;
        }
        if(token.startsWith("Bearer ")){
            token = token.substring(7);
        };

        String u = stringRedisTemplate.opsForValue().get(SysConstant.loing_user_key + token);
        if (u != null && u.isEmpty()) {
            response.setStatus(401);
            System.out.println("token已过期，拦截");
            return false;
        }

        // 更新过期时间
        stringRedisTemplate.expire(SysConstant.loing_user_key + token, Duration.ofDays(30 * 60 * 1000));
        System.out.println("----------------放行");
        return true;
    }
}